package com.david.andserver

import android.app.*
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.content.Intent
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.david.core.event.MyEventBus
import com.david.core.utils.ToastUtils

class ServerService: Service() {

    companion object{
        const val SERVER_START_KEY = "server_command"
        const val SERVER_START_COMMAND = 1
        const val SERVER_STOP_COMMAND = 2
    }

    private var mServerManager: ServerManager? = null

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        if (mServerManager == null) {
            mServerManager = ServerManager(this)
        }


//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startNotification()
//        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent != null) {
            when(intent.getIntExtra(SERVER_START_KEY, -1)) {
                SERVER_START_COMMAND -> {
                    if (!mServerManager?.isServerRunning!!) {
                        mServerManager?.startServer()
                        val event = ServerStatusEvent()
                        event.isRunning = true
                        MyEventBus.getDefault().post(event)
                    } else {
                        ToastUtils.instance.toast("服务已经开启！")
                    }
                }
                SERVER_STOP_COMMAND -> {
                    if (mServerManager?.isServerRunning!!) {
                        mServerManager?.stopServer()

                        val event = ServerStatusEvent()
                        event.isRunning = false
                        MyEventBus.getDefault().post(event)
                    } else {
                        if (!ToastUtils.instance.isInited()) {
                            ToastUtils.instance.init(applicationContext)
                        }
                        ToastUtils.instance.toast("服务已经停止！")
                    }
                }
            }
        }

        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mServerManager != null) {
            mServerManager!!.stopServer() //停止服务器
        }
    }


    /**
     * 启动一个前台通知，但通知栏会显示一个通知栏
     */
    private fun startNotification() {
        val builder: NotificationCompat.Builder = NotificationCompat.Builder(this, "server")
        builder.setContentTitle("andServer")
        builder.setContentText("andServer running...")
        builder.setSmallIcon(R.mipmap.ic_logo)
        builder.setContentIntent(PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), FLAG_IMMUTABLE))

        val silentChannel = NotificationChannel(
            "server",
            "andServer",
            NotificationManager.IMPORTANCE_HIGH
        )
        silentChannel.name = "server is running..."
        silentChannel.setSound(null, null)
        silentChannel.enableVibration(false)
        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        manager.createNotificationChannel(silentChannel)

        // 这里两个通知使用同一个id且必须按照这个顺序后调用startForeground
        val id = 2
//                        NotificationManagerCompat.from(this).notify(id, builder.build());
        startForeground(id, builder.build())
    }
}